import Zombie from './zombie';

/**
 * 僵尸管理类
 * 负责控制僵尸的生成和管理
 */
export default class ZombieManager {
  /**
   * 构造函数
   * @param {number} spawnInterval - 每多少帧生成一个僵尸
   * @param {string} zombieImgPrefix - 僵尸图片路径前缀
   * @param {number} zombieFrameCount - 僵尸动画帧数
   * @param {number} zombieWidth - 僵尸宽度
   * @param {number} zombieHeight - 僵尸高度
   * @param {number} zombieSpeed - 僵尸移动速度
   * @param {number} maxY - 僵尸最大Y坐标
   */
  constructor(
      spawnInterval = 60,
      zombieWidth = 80,
      zombieHeight = 100,
      zombieFrameInterval = 6,
      zombieSpeed = 1,
      maxY = canvas.height-100
    ) {
      // 定义两种僵尸配置
      this.zombieConfigs = [
        {
          imgPrefix: 'graphics/Zombies/ConeheadZombie/ConeheadZombie/ConeheadZombie_',
          frameCount: 20,
          zombieWidth : 100,
          zombieHeight : 120,
        },
        {
          imgPrefix: 'images/one/f',
          frameCount: 6,
          zombieWidth : 75,
          zombieHeight : 134,
        }
      ];


    this.spawnInterval = spawnInterval; // 生成间隔帧数
    this.frameCounter = 10000; // 一开始就生成一个僵尸
    this.zombies = []; // 僵尸数组
    this.timeCounter = 0; // 时间计数器，用于控制每5秒减少spawnInterval
    
    // 僵尸配置
   
    this.zombieWidth = zombieWidth;
    this.zombieHeight = zombieHeight;
    this.zombieSpeed = zombieSpeed;
    this.maxY = maxY;
    this.zombieFrameInterval = zombieFrameInterval;
  }

  /**
   * 更新方法
   * 检查是否需要生成新僵尸，并更新所有僵尸的状态
   */
  update() {
    this.frameCounter++;
    this.timeCounter++;
    
    // 加速僵尸生成
    if (this.timeCounter >= 50) {
      if (this.spawnInterval > 10) { // 确保spawnInterval不会太小
        this.spawnInterval--;
      }
      this.timeCounter = 0;
    }

    // 检查是否需要生成新僵尸
    if (this.frameCounter >= this.spawnInterval) {
      this.spawnZombie();
      this.frameCounter = 0;
    }

    // 更新所有僵尸
    for (let i = 0; i < this.zombies.length; i++) {
      const zombie = this.zombies[i];
      zombie.update();

      // 检查僵尸是否死亡
      if (zombie.isDead) {
        // 回收僵尸到对象池
        GameGlobal.databus.pool.recover('zombie', zombie);
        this.zombies.splice(i, 1);
        i--;
      }
    }
  }

  /**
   * 渲染方法
   * 绘制所有僵尸
   * @param {CanvasRenderingContext2D} ctx - 绘图上下文
   */
  render(ctx) {
    for (const zombie of this.zombies) {
      zombie.render(ctx);
    }
  }

  /**
   * 生成新僵尸
   */
  spawnZombie() {
    const zombie = GameGlobal.databus.pool.getItemByClass('zombie', Zombie);
    // 随机选择一种配置
    const configIndex = Math.floor(Math.random() * this.zombieConfigs.length);
    const config = this.zombieConfigs[configIndex];
    zombie.init(
        config.imgPrefix,
        config.frameCount,
        config.zombieWidth,
        config.zombieHeight,
        this.zombieFrameInterval,
        this.zombieSpeed,
        this.maxY
      );
    this.zombies.push(zombie);
  }

  /**
   * 设置生成间隔
   * @param {number} interval - 新的生成间隔帧数
   */
  setSpawnInterval(interval) {
    this.spawnInterval = interval;
  }
}